package com.yx.learn.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.yx.learn.domain.Authority;
import com.yx.learn.domain.User;
import com.yx.learn.service.UserAuthorityService;
import com.yx.learn.service.UserService;
import com.yx.learn.util.TreeAndToJsonUtil;

@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String employNo;
	private String password;
	public User user =new User();
	
	@Resource
	private UserService userService;

	@Resource
	private UserAuthorityService userAuthorityService;

	// 登录方法
	public String login() {

		try {
			if (employNo.length() == 0 || employNo.equals("")
					|| password.length() == 0 || password.equals("")) {
				addActionError("用户名或者密码不能为空！");
				return INPUT;
			} else {
				user = userService.checkUser(employNo, password);
				if (user == null) {
					addActionError("用户名或者密码错误！");
					return INPUT;
				} else {
					System.out.println(user.getEmployName());
					session.setAttribute("user", user);
					//用户全部权限，用于权限拦截
					List<Authority> list = userAuthorityService
							.getUserAuthorityByNo(employNo);
					session.setAttribute("userAuthorities", list);
					//用户的菜单权限
					List<Authority> menulist = userAuthorityService
					.getUserAuthorityOfMenuByNo(employNo);
					//将菜单级别的权限处理
					TreeAndToJsonUtil tatju = new TreeAndToJsonUtil(menulist);
					//先将权限信息构造成树形结构
					tatju.createAuthorityTreeMap();
					// 将树形结构转换成json数据，并放入session
					session.setAttribute("treeMenu", tatju.authorityTreeMapToJSONArray(-1));
					return SUCCESS;
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
	}

	public String getEmployNo() {
		return employNo;
	}

	public void setEmployNo(String employNo) {
		this.employNo = employNo;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpSession session = request.getSession();

	
	

}
